package com.yay.danceline.util;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.google.ads.AdActivity;
import com.yay.danceline.ui.HomeActivity;
import com.yay.danceline.ui.DLApplication;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;


/**
 * Get Started!
 * @author yakovlev.yuriy@gmail.com
 * @author Dmitry Makeev
 */
public class UIUtilsNew {
	private static final String TAG = "UIUtils";
    private static Boolean isOnline;
    private static final String SERVER_URL = "http://getstarted.com.ua/recipes/images/";
    private static final String SERVER_URL_LARGE = "http://m5i.s3.amazonaws.com/";
    private static String S1 = "%s%d.jpg"; 
    private static String S2 = "%s%d.png"; 
    
    
    public static boolean isOnline(Context context, boolean force) {
		if(isOnline == null || force) {
			try {
				final ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
				final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
				if(activeNetwork != null && activeNetwork.getState() == NetworkInfo.State.CONNECTED) {
				    isOnline = true;
				} else {
				    isOnline = false;
				} 
			} catch(Exception e) {
				Log.e(TAG, e.toString());
				isOnline = false;
			}
		}
		return isOnline;
	}
    
    public static Drawable fetchDrawable(int id) {
    	return fetchDrawable(id, null);
    }
    
    public static Drawable fetchDrawable(int id, AdActivity adActivity) {
    	Drawable drawable = null;
    	String idl = id+"l";
    	
    	if(adActivity != null && DLApplication.getInstance().getDrawableHashMap().containsKey(idl)) {
            return DLApplication.getInstance().getDrawableHashMap().get(idl).get();
        }
        InputStream is = null;
        try {
            is = fetch(id, adActivity);
            drawable = Drawable.createFromStream(is, "src");
            
            if(drawable != null) {
            	DLApplication.getInstance().getDrawableHashMap().put(adActivity!=null? idl : id, new SoftReference<Drawable>(drawable));
	        }
        } catch (Exception e) {
            Log.e(TAG, "fetchDrawable failed", e);
        } finally {
            if(is != null) {
                try { is.close(); } catch (IOException e) {	}
            }
        }
        return drawable;
    }
    
    public static void fetchDrawableOnThread(final int id, final View imageView) {
    	fetchDrawableOnThread(id, imageView, null);
    }
    public static void fetchDrawableOnThread(final int id, final View imageView, final AdActivity adActivity) {
        if(adActivity == null && DLApplication.getInstance().getDrawableHashMap().containsKey(id)) {
            imageView.setBackgroundDrawable(DLApplication.getInstance().getDrawableHashMap().get(id).get());
        }

        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message message) {
            	Drawable drawable = (Drawable) message.obj;
            	if(drawable == null) {
            		if(adActivity != null) {
            			fetchDrawableOnThread(id, imageView, null);
            		} else {
            			imageView.setVisibility(View.GONE);
            		}
            	} else {
            		/*if(adActivity != null && !RecipeActivity.adClicked) {
            			adActivity.initAdLayout();
            		}*/
            		imageView.setBackgroundDrawable(drawable);
            	}
            }
        };

        Thread thread = new Thread() {
            @Override
            public void run() {
                //TODO : set imageView to a "pending" image
            	Drawable drawable = fetchDrawable(id, adActivity);
                Message message = handler.obtainMessage(1, drawable);
                handler.sendMessage(message);
            }
        };
        thread.start();
    }

    private static InputStream fetch(int id, AdActivity adActivity) throws MalformedURLException, IOException {
    	String urlString = null;
    	if(adActivity != null) {
    		urlString = String.format(S1, SERVER_URL_LARGE, id);
    	} else {
    		urlString = String.format(S2, SERVER_URL, id);
    	}
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet request = new HttpGet(urlString);
        HttpResponse response = httpClient.execute(request);
        return response.getEntity().getContent();
    }

    /**
     * Invoke "home" action, returning to {@link HomeActivity}.
     */
    public static void goHome(Context context) {
        final Intent intent = new Intent(context, HomeActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

    /**
     * Invoke "search" action, triggering a default search.
     */
    public static void goSearch(Activity activity) {
        activity.startSearch(null, false, Bundle.EMPTY, false);
    }

    /**
     * Populate the given {@link TextView} with the requested text, formatting
     * through {@link Html#fromHtml(String)} when applicable. Also sets
     * {@link TextView#setMovementMethod} so inline links are handled.
     */
    public static void setTextMaybeHtml(TextView view, String text) {
        if (text.contains("<") && text.contains(">")) {
            view.setText(Html.fromHtml(text));
            view.setMovementMethod(LinkMovementMethod.getInstance());
        } else {
            view.setText(text);
        }
    }

}
